#!/usr/bin/env bash
#vim
function vd() {
  vu -d $*
}
function vu() {
  local _vu="vim -u ${shell_dir}/.vimrc"
  local files_to_open
  if [[ "$1" ]]; then
    if [[ -e $1 ]]; then
      $_vu $*
    elif [[ $# -gt 1 ]]; then
      $_vu $*
    else
      files_to_open="$(multi_select "$(git ls-files 2>/dev/null | grep $1)" 2>/dev/null)"
      if [[ $files_to_open ]]; then
        $_vu -p $files_to_open
      else
        $_vu $*
      fi
    fi
  else
    $_vu
  fi
}
function grepkill() {
  # TODO reuse the grep results
  ps -ef | grep -iP "$(echo $* | sed '{s/\s+/\s/;s/^\s*//;s/\s*$//;}' | sed 's/\s/\|/g')" | grep -v grep
  read -p '确定杀死这些进程？'
  ps -ef | grep -iP "$(echo $* | sed '{s/\s+/\s/;s/^\s*//;s/\s*$//;}' | sed 's/\s/\|/g')" | grep -v grep | \
    awk '{print $2}' | xargs -i kill -9 {}
}
function su_without_password() {
  local target_user from_user
  if [[ -z "${1+x}" ]]
  then
    echo '/etc/pam.d/su'
    echo '$1 target_user $2 from_user'
  fi
  target_user=$1
  from_user=$2
  read -d '' OUT <<EOT
auth       [success=ignore default=1] pam_succeed_if.so user = $target_user
auth       sufficient   pam_succeed_if.so use_uid user = $from_user
EOT
  echo "$OUT"
}

function nocolor() {
  sed 's/\x1b\[[0-9;]*m//g'
}

function mktouch() {
  local f
  if [[ $# -lt 1 ]]; then
    echo "Missing argument";
    return 1;
  fi

  for f in "$@"; do
    mkdir -p -- "$(dirname -- "$f")"
    touch -- "$( echo $f | tr -s / | sed 's/\/$//' )"
  done
}

function whereip() {
  local _curl="curl -A 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36' -s"
  $_curl https://ip.cn?ip=${1} | grep --color=never -oP '(?<=<code>).*?(?=</code>)'
}
function getip() {
  whereip "$@" | grep --color=never -oP '\d{1,3}(\.\d{1,3}){3}'
}

function straceall() {
  strace "${@:2}" $(pgrep "${1}" | xargs | sed 's/[0-9]\+/-p &/g')
}
function mkver() {
  local _filename _extension _tmp_filename _add _real_tmp
  if [[ -e $1 ]]; then
    if [[ $1 =~ \. ]]; then
      _filename=${1%.*}
      _extension=${1##*.}
    else
      _filename=$1
    fi
  else
    echo 'no found'
    return
  fi
  if [[ -n $_filename ]]; then
    _add="-$(date +%Y%m%d)-XXX"
  else
    _add="$(date +%Y%m%d)-XXX"
  fi
  _extension=${_extension:=}
  _tmp_filename="$_filename${_add}${_extension:+.$_extension}"
  _real_tmp=$(mktemp --tmpdir=$(pwd) -t "$_tmp_filename")
  cp $1 $_real_tmp
}
__dfa()
{
  local cur prev opts funs aliases

  COMPREPLY=()
  cur="${COMP_WORDS[COMP_CWORD]}"
  # prev="${COMP_WORDS[COMP_CWORD-1]}"
  funs="$(declare -F | awk '{print $3}' | xargs)"
  aliases="$(alias | awk '/^alias/{print $2}' | cut -d'=' -f1)"
  opts="${aliases-} ${funs-}"

  _get_comp_words_by_ref -n : cur
  COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
  __ltrim_colon_completions "$cur"
}
complete -F __dfa dfa
function dfa() {
  local info _alias
  info=$(declare -f $1)
  _alias=$(alias "$1" 2>/dev/null)
  if [[ -n "$_alias" ]]; then
    echo "$_alias"
  elif [[ -n "$info" ]]; then
    echo "$info"
  else
    echo 'definition not found'
  fi
}
# genereate password
function getpwd() {
	head -c 1000 /dev/urandom | tr -dc a-z0-9A-Z~@#$%^ | head -c ${1-8};echo
  echo
}
function getabc() {
	head -c 1000 /dev/urandom | tr -dc a-z0-9A-Z | head -c ${1-8};echo
  echo
}
function load_alias() {
  alias ${alias:-} &>/dev/null
}
function retry() {
  load_alias
  local tm
  while true
  do
    tm=$(date +%s)
    eval $@ &&  echo '------ok--------'$tm || echo '------err--------'$tm
    sleep ${n-1}
  done
}
#function man(){
#  vim -c 'execute "normal! :let no_man_maps = 1\<cr>:runtime ftplugin/man.vim\<cr>:Man '"$*"'\<cr>:wincmd o\<cr>"'
#}
# function wine() {
  # local _dir=${1-.}
  # if [[ -f $_dir ]];then
    # _dir="$(dirname $_dir)"
  # fi
  # cd $_dir
  # explorer .
  # cd - >/dev/null
# }

function debug() {
  bash -ixc "export SHELLOPTS; $*"
}
function tssh() {
  CUR_PANE=$(tmux list-panes | grep "active" | cut -d':' -f1)
  for host in ${@:2} ; do
    tmux splitw -v ssh $host
  done
  tmux select-pane -t $CUR_PANE; ssh ${1}
}
function uniq_file() {
  echo "$(uniq $1)" > $1
}
function watchpath() {
  $@
  inotifywait -e close_write -qmr ${watch_dirs:-.} --format '%w%f %e %T' --timefmt '%H%M%S' | while read file event timestamp; do
    if [[ "$file" =~ (~$|^[0-9]+$) ]];then
      # 临时文件
      continue;
    fi

    current=$(date +'%H%M%S')
    delta=`expr $current - $timestamp`

    if [ $delta -lt 2 -a $delta -gt -2 ] ; then
      sleep .5 # sleep 1 set to let file operations end
        watch_path=$(pwd) file=$file event=$event timestamp=$timestamp $@
      sleep .5 
    fi
  done
}
function watchfile() {
  load_alias
  local file last_time real_time
  file=$1
  shift
  last_time=""
  while true
  do
    real_time=$(stat -c '%Y' $file)
    if [[ "$last_time" != $real_time ]]; then
      last_time=$real_time
      eval $@ &&  echo '------ok--------'$real_time || echo '------err--------'$real_time
    fi
    sleep ${n:-1}
  done
}
function atoi {
  #Returns the integer representation of an IP arg, passed in ascii dotted-decimal notation (x.x.x.x)
  IP=$1; IPNUM=0
  for (( i=0 ; i<4 ; ++i )); do
    ((IPNUM+=${IP%%.*}*$((256**$((3-${i}))))))
    IP=${IP#*.}
  done
  echo $IPNUM 
} 

function itoa {
  #returns the dotted-decimal ascii form of an IP arg passed in integer format
  echo -n $(($(($(($((${1}/256))/256))/256))%256)).
  echo -n $(($(($((${1}/256))/256))%256)).
  echo -n $(($((${1}/256))%256)).
  echo $((${1}%256)) 
}
